package com.serializeQueue;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

/*
    任务队列构建器

    创建对象:使用静态of方法

    可以指定:
        1.核心线程池数量
        2.任务持久化器
        3.过期任务处理器
        4.异常处理器

 */
public class TaskQueueBuilder<T extends SerializableTask> {

    private int core = 1;

    private TaskSerializer<T> taskSerializer;

    private ExceptionHandler<T> exceptionHandler;

    private ExpiredTaskHandler<T> expiredTaskHandler;

    public static <E extends SerializableTask> TaskQueueBuilder<E> of(Class<E> clazz) {
        return new TaskQueueBuilder<E>();
    }

    private TaskQueueBuilder() {
    }


    public TaskQueueBuilder<T> coreExecutor(int core) {
        this.core = core;
        return this;
    }

    public TaskQueueBuilder<T> taskSerializer(TaskSerializer<T> taskSerializer) {
        this.taskSerializer = taskSerializer;
        return this;
    }

    public TaskQueueBuilder<T> exceptionHandler(ExceptionHandler<T> exceptionHandler) {
        this.exceptionHandler = exceptionHandler;
        return this;
    }

    public TaskQueueBuilder<T> expiredTaskHandler(ExpiredTaskHandler<T> expiredTaskHandler) {
        this.expiredTaskHandler = expiredTaskHandler;
        return this;
    }



    public TaskQueue<T> build() {

        TaskQueue<T> queue = new TaskQueue<T>();

        queue.service = Executors.newScheduledThreadPool(core);


        if (taskSerializer != null) {
            queue.serializer = taskSerializer;
        } else {
            queue.serializer = defaultTaskSerializer;
        }

        if (exceptionHandler != null) {
            queue.handler = exceptionHandler;
        } else {
            queue.handler = defaultExceptionHandler;
        }

        if (exceptionHandler != null) {
            queue.expiredTaskHandler = expiredTaskHandler;
        } else {
            queue.expiredTaskHandler = defaultExpiredTaskHandler;
        }

        //初始化
        queue.init();

        return queue;

    }

    //默认的持久化器,将任务持久化在内存中
    private static TaskSerializer defaultTaskSerializer = new TaskSerializer() {

        Map<String, SerializableTask> map = new HashMap<>();

        @Override
        public void serialize(SerializableTask serializableTask) {
            map.put(serializableTask.getId(), serializableTask);
        }

        @Override
        public void remove(String id) {
            map.remove(id);
        }

        @Override
        public List<SerializableTask> allTasks() {
            return Collections.EMPTY_LIST;
        }

    };

    private static ExceptionHandler defaultExceptionHandler = (task, e) -> System.out.println("默认的异常处理器:"+task.getId() + "   处理失败  " + e);

    private static ExpiredTaskHandler defaultExpiredTaskHandler = (task) -> System.out.println("默认的过期任务处理器   :" + task.getId() + "  过期,创建时间:" + task.getCreateTime());

}
